package com.css.devops.monitor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import java.io.StringReader;

public class JenkinsJobService {

    private static final String JENKINS_URL = "http://192.168.94.1:18080";
    private static final String JOB_NAME = "fresco-web";
    private static final String JOB_BRANCH = "master";
    private static final String API_TOKEN = "p@ssw0rd"; // 替换为你的 API Token
    private static final String USERNAME = "admin"; // 替换为你的 Jenkins 用户名

    public static void main(String[] args) {
        try {
            // 构建最后一次构建的 URL
            String buildUrl = String.format("%s/job/%s/job/%s/lastBuild/api/xml", JENKINS_URL, JOB_NAME, JOB_BRANCH);
            String response = sendRequest(buildUrl, USERNAME, API_TOKEN);
            parseAndPrintXml(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String sendRequest(String apiUrl, String username, String apiToken) throws Exception {
        URL url = new URL(apiUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setInstanceFollowRedirects(false); // 禁用自动重定向

        // 添加认证信息
        String userCredentials = username + ":" + apiToken;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes());
        connection.setRequestProperty("Authorization", basicAuth);

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
            String newLocation = connection.getHeaderField("Location");
            System.out.println("Redirected to: " + newLocation);
            // 构建完整的重定向 URL
            if (newLocation.startsWith("/")) {
                newLocation = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + newLocation;
            }
            // 递归调用处理重定向
            return sendRequest(newLocation, username, apiToken);
        } else if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new Exception("HTTP error code: " + responseCode);
        }
    }


    private static void parseAndPrintXml(String xmlResponse) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xmlResponse)));

        // 解析 XML 数据
        NodeList resultNodes = document.getElementsByTagName("result");
        NodeList urlNodes = document.getElementsByTagName("url");
        NodeList timestampNodes = document.getElementsByTagName("timestamp");
        NodeList numberNodes = document.getElementsByTagName("number");
        NodeList displayNameNodes = document.getElementsByTagName("displayName");
        NodeList durationNodes = document.getElementsByTagName("duration");
        NodeList fullDisplayNameNodes = document.getElementsByTagName("fullDisplayName");

        if (resultNodes.getLength() > 0 && urlNodes.getLength() > 0) {
            String buildResult = resultNodes.item(0).getTextContent();
            String buildUrl = urlNodes.item(0).getTextContent();
            String buildTimestamp = timestampNodes.getLength() > 0 ? timestampNodes.item(0).getTextContent() : "";
            String buildNumber = numberNodes.item(0).getTextContent();
            String displayName = displayNameNodes.item(0).getTextContent();
            DateTime datetime = DateUtil.date(Long.valueOf(buildTimestamp));
            String duration = durationNodes.item(0).getTextContent();
            String fullDisplayName = fullDisplayNameNodes.item(0).getTextContent();
            
            System.out.println("构建结果: " + buildResult);
            System.out.println("构建URL: " + buildUrl);
            System.out.println("构建开始时间: " + datetime);
            System.out.println("构建耗时: " + Long.valueOf(duration)/1000);
            System.out.println("构建版本: " + buildNumber);
            System.out.println("构建名称: " + displayName);
            System.out.println("构建全名称: " + fullDisplayName);
        } else {
            System.out.println("No result or URL found in the XML response.");
        }
    }


}




